import { defineStore } from "pinia";


const useUserStore = defineStore("user", {
	id: "user",

	// 数据
	state: () => {
		return {
			username: '',
			password: '',
			email: '',
			sex: '',
			age: '',
			phone: '',
			address: '',
			readme: '',
			goodsCart: []
		}
	},

	// 获取数据
	getters: {
		// 获取购物车数据
		getGoodsCart: (state) => state.goodsCart,

		// 获取购物车总金额
		getTotalPrice: (state) => {
			const total = state.goodsCart.reduce((pre, cur) => {
				return pre + (Number(cur.price) * cur.count)
			}, 0);

			return total;
		}
	},

	// 修改数据
	actions: {

		// 退出登录
		clearUserInfo() {
			this.$patch({
				username: '',
				password: ''
			})
		},

		// 修改用户信息
		updateUserInfo(info) {
			this.$patch({...this.state, ...info})
		},

		// 添加购物车
		addGoodsCart(goods) {
			const { id, count } = goods;

			const currGoods = this.goodsCart.find(item => item.id === id);

			if (currGoods) {
				currGoods.count = currGoods.count + count;
				this.goodsCart = [...this.goodsCart];
			} else {
				this.goodsCart = [...this.goodsCart, goods];
			}
		},

		// 移除购物车
		removeGoodsCart(id) {
			this.goodsCart = this.goodsCart.filter(item => item.id !== id)
		}
	},

	// 开启数据持久化
  persist: true,
})

export default useUserStore